package com.example.boot.http.consumer.client;

import com.example.boot.http.consumer.bean.User;
import com.example.boot.http.consumer.common.Result;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class BootJSONClient {

    private static final String PREFIX_URL = "http://localhost:8090/boot/provider/json";

    public static void main(String[] args) {
        BootJSONClient bootJSONClient = new BootJSONClient();
        System.out.println("bootJSONClient.get ---> " + bootJSONClient.get(1));
        User user = new User("boot-json", 15);
        System.out.println("bootJSONClient.add ---> " + bootJSONClient.add(user));
    }

    public User add(User user) {
        String urlString = PREFIX_URL + "/add";
        Result<User> result = new RestTemplate().exchange(urlString, HttpMethod.POST,
                new HttpEntity<>(user, null),
                new ParameterizedTypeReference<Result<User>>() {
                }).getBody();
        return result == null ? null : result.getData();
    }

    public User get(Integer id) {
        Map<String, Integer> uriVariables = new HashMap<>();
        uriVariables.put("id", id);
        String urlString = PREFIX_URL + "/get/{id}";
        Result<User> result = new RestTemplate().exchange(urlString, HttpMethod.GET,
                new HttpEntity<>(null, null),
                new ParameterizedTypeReference<Result<User>>() {
                },
                uriVariables).getBody();
        return result == null ? null : result.getData();
    }

}
